package com.wq.httpclientcore.controller;

import com.fasterxml.jackson.core.type.TypeReference;
import cn.hutool.core.net.URLDecoder;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.wq.httpclientcore.common.CommonClient;
import com.wq.httpclientcore.model.HttpResponseWrapper;
import com.wq.httpclientcore.service.DynamicQueryService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/common")
@Tag(name = "通用 查询 调用", description = "提供通用的 API和Query 调用接口")
public class CommonController {

    @Autowired
    private CommonClient commonClient;

    private ObjectMapper objectMapper = new ObjectMapper();

    @GetMapping("/callApi/{apiId}")
    @Operation(summary = "调用指定 API", description = "根据 API ID 调用对应的 API，并可传入动态参数、动态请求头和动态请求体")
    @ApiResponse(responseCode = "200", description = "成功调用 API", content = @Content(schema = @Schema(implementation = HttpResponseWrapper.class)))
    @ApiResponse(responseCode = "400", description = "参数格式错误，请检查输入的 JSON 格式", content = @Content(schema = @Schema(implementation = HttpResponseWrapper.class)))
    @ApiResponse(responseCode = "404", description = "未找到或禁用 API", content = @Content(schema = @Schema(implementation = HttpResponseWrapper.class)))
    @ApiResponse(responseCode = "500", description = "请求失败", content = @Content(schema = @Schema(implementation = HttpResponseWrapper.class)))
    public HttpResponseWrapper<?> callApi(
            @Parameter(description = "API 的 ID", required = true) @PathVariable Long apiId,
            @Parameter(description = "动态请求参数，JSON 格式的字符串", required = false) @RequestParam(required = false) String dynamicParams,
            @Parameter(description = "动态请求头，JSON 格式的字符串", required = false) @RequestParam(required = false) String dynamicHeaders,
            @Parameter(description = "动态请求体，JSON 格式的字符串", required = false) @RequestParam(required = false) String dynamicBody,
            @Parameter(description = "分页大小", required = false) @RequestParam(required = false) Integer pageSize,
            @Parameter(description = "分页页码", required = false) @RequestParam(required = false)Integer pageNo) {
        Map<String, Object> dynamicParamsMap = new HashMap<>();
        Map<String, String> dynamicHeadersMap = new HashMap<>();
        Map<String, Object> dynamicBodyObj= new HashMap<>();

        try {
            if (dynamicParams != null && !dynamicParams.isEmpty()) {
                dynamicParamsMap = parseJsonParams(dynamicParams);
            }
            if (dynamicHeaders != null && !dynamicHeaders.isEmpty()) {
                dynamicHeadersMap = parseJsonParams2(dynamicHeaders);
            }
            if (dynamicBody != null && !dynamicBody.isEmpty()) {
                dynamicBodyObj = parseJsonParams(dynamicBody);
            }
        } catch (Exception e) {
            return new HttpResponseWrapper<>(null, 400, "参数格式错误，请检查输入的 JSON 格式",null);
        }

        return commonClient.callApi(apiId, dynamicParamsMap, dynamicHeadersMap, dynamicBodyObj,pageSize, pageNo);
    }

    private Map<String, Object> parseJsonParams(String json) throws JsonProcessingException {
        if (json == null || json.isEmpty()) return new HashMap<>();
        // 手动解码 URL 编码
        String decoded = URLDecoder.decode(json, StandardCharsets.UTF_8);
        return objectMapper.readValue(decoded, new TypeReference<Map<String, Object>>() {});
    }

    private Map<String, String> parseJsonParams2(String json) throws JsonProcessingException {
        if (json == null || json.isEmpty()) return new HashMap<>();
        // 手动解码 URL 编码
        String decoded = URLDecoder.decode(json, StandardCharsets.UTF_8);
        return objectMapper.readValue(decoded, new TypeReference<Map<String, String>>() {});
    }

    @Autowired
    private DynamicQueryService dynamicQueryService;

    @GetMapping("/executeDbQuery/{queryConfigId}")
    @Operation(summary = "执行数据库查询", description = "根据查询配置ID执行预定义的SQL查询")
    @ApiResponse(responseCode = "200", description = "查询成功", content = @Content(schema = @Schema(implementation = HttpResponseWrapper.class)))
    public HttpResponseWrapper<?> executeDbQuery(
            @Parameter(description = "数据库查询配置ID", required = true) @PathVariable Long queryConfigId,
            @Parameter(description = "分页大小") @RequestParam(required = false) Integer pageSize,
            @Parameter(description = "分页页码") @RequestParam(required = false) Integer pageNo) {

        try {
            List<Map<String, Object>> result = dynamicQueryService.executeQuery(queryConfigId, pageSize, pageNo);
            return new HttpResponseWrapper<>(result, 200, null, result.size());
        } catch (Exception e) {
            return new HttpResponseWrapper<>(null, 500, e.getMessage(),0);
        }
    }

}